import { computed, ref, toValue, watchEffect } from "vue";
import dayjs from "dayjs";
import { BuyerUserDetils, MyPageView } from "../../api/xpert";
import { useLocalStorage } from "../../hooks/localStorage";

// 是否卖家
// 3买家，2卖家
const isSeller = () => {
	const ind = window.localStorage.getItem("ind");
	return ["2"].includes(ind);
};

// 获取用户id
export const getUserId = str => {
	return `${str}`.split("_").at(0);
};

export const useConversationList = (conversations, { search } = {}) => {
	const list = ref([]);

	const { userId } = useLocalStorage("userInfo", {});

	const fn = isSeller() ? MyPageView : BuyerUserDetils;

	watchEffect(async () => {
		const all = await Promise.all(
			toValue(conversations).map(async conversation => {
				let participants;
				try {
					participants = await conversation.getParticipants();
				} catch {
					// console.error(e);
					return false;
				}
				// 这里固定获取[1],因为useCommunication插入输入为1
				if (!participants[1]) {
					return false;
				}
				const id = getUserId(participants[1].identity);
				if (userId == id) {
					return false;
				}

				const { dateUpdated, uniqueName } = conversation;

				return {
					id,
					time: dayjs(dateUpdated).format("HH:mm"),
					// 会话id
					uniqueName,
					partyId: participants[1].identity
				};
			})
		);

		const result = await Promise.all(
			all
				.filter(f => f)
				.map(async obj => {
					const result = await fn({ userId: obj.id });

					return {
						...obj,
						...result.data
					};
				})
		);
		list.value = result;
	});

	const filterResults = computed(() => {
		return list.value.filter(f => {
			if (toValue(search)) {
				return f.username.includes(toValue(search));
			}
			return true;
		});
	});

	return filterResults;
};
